import 'package:dio/dio.dart';

// 自定义 http 异常
class CustomHttpException implements Exception {
  final int code;
  final String message;

  CustomHttpException({
    this.code = 500,
    this.message = '未知异常，请联系管理员',
  });

  @override
  String toString() {
    return "HttpError [$code]: $message";
  }

  factory CustomHttpException.create(DioException error) {
    // dio 异常
    switch (error.type) {
      case DioExceptionType.cancel:
        return CustomHttpException(code: -1, message: '请求已取消');
      case DioExceptionType.connectionTimeout:
        return CustomHttpException(code: -1, message: '连接超时，请稍后重试');
      case DioExceptionType.sendTimeout:
        return CustomHttpException(code: -1, message: '请求超时，请稍后重试');
      case DioExceptionType.receiveTimeout:
        return CustomHttpException(code: -1, message: '服务器响应超时，请稍后重试');
      case DioExceptionType.badResponse:
        // 服务器异常
        int? statusCode = error.response?.statusCode;
        switch (statusCode) {
          case 400:
            return CustomHttpException(code: statusCode!, message: '请求语法错误');
          case 401:
            return CustomHttpException(code: statusCode!, message: '没有权限');
          case 403:
            return CustomHttpException(code: statusCode!, message: '服务器拒绝执行');
          case 404:
            return CustomHttpException(code: statusCode!, message: '无法连接服务器');
          case 500:
            return CustomHttpException(code: statusCode!, message: '服务器内部错误');
          case 502:
            return CustomHttpException(code: statusCode!, message: '无效的请求');
          case 503:
            return CustomHttpException(code: statusCode!, message: '服务器挂了');
          case 505:
            return CustomHttpException(
                code: statusCode!, message: '不支持HTTP协议请求');
          default:
            return CustomHttpException(
              code: statusCode ?? 500,
              message: error.response?.statusMessage ?? '未知异常，请联系管理员',
            );
        }
      default:
        return CustomHttpException(
          code: 500,
          message: error.message ?? '未知异常，请联系管理员',
        );
    }
  }
}
